# -*- coding: utf-8 -*-
"""
Created on Fri May 12 15:27:44 2017

@function: handWriting recognition with KNN algorithm from scikit-learn
"""

from os import listdir
import numpy as np  
from sklearn import neighbors  
import cv2

#function: get format mat-txt from picture
#input: picture name, output txt name
#output mat-txt name
def pic2txt(pic_name, txt_name):
    try:
        pic = cv2.imread(pic_name)
        pic = cv2.resize(pic, (32,32), interpolation=cv2.INTER_CUBIC)
        pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
        thresh, pic = cv2.threshold(pic, 240, 1, cv2.THRESH_BINARY_INV)
        np.savetxt(txt_name, pic, fmt = '%i', delimiter = '')
    except:
        print 'error to convert pic into txt'
        return -1
    return txt_name

#function: get feature vector from file
#input: file name, file size 
#output: feature vector
def img2vector(filename, sz=32):
    returnVect = np.zeros((1,sz*sz))
    fr = open(filename)
    for i in range(sz):
        lineStr = fr.readline()
        for j in range(sz):
            returnVect[0,sz*i+j] = int(lineStr[j])
    return returnVect


#function: handwriting recognition
#input: 0-1 feature vector
#output: possible figure

def handwritingRecognition(In_x):
    hwLabels = []
    trainingFileList = listdir('trainingDigits')           #load the training set
    m = len(trainingFileList)
    trainingMat = np.zeros((m,1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr, 32)
    
    in_x = img2vector(In_x, 32)
    knn = neighbors.KNeighborsClassifier() #取得knn分类器 
    hwLabels = np.array(hwLabels)
    knn.fit(trainingMat, hwLabels)
    xType = knn.predict(in_x)
    return xType



#function: model test
def handwritingTest():
    testFileList = listdir('testDigits')        #iterate through the test set
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        classifierResult = handwritingRecognition('testDigits/%s' % fileNameStr)
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)
        if (classifierResult != classNumStr): errorCount += 1.0
    print "\nthe total number of errors is: %d" % errorCount
    print "\nthe total error rate is: %f" % (errorCount/float(mTest))
 